package com.yq.cp.controller.basics;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.cp.config.UserThreadLocal;
import com.yq.cp.entity.basics.BillingInformationSettings;
import com.yq.cp.entity.basics.EquipmentManagement;
import com.yq.cp.entity.basics.OrganizationalStructure;
import com.yq.cp.entity.basics.TotalSettlement;
import com.yq.cp.entity.common.ApiResult;
import com.yq.cp.entity.common.PageVo;
import com.yq.cp.entity.permission.User;
import com.yq.cp.service.basics.EquipmentManagementService;
import com.yq.cp.service.basics.OrganizationalStructureService;
import com.yq.cp.service.basics.TotalSettlementService;
import com.yq.cp.utils.DateTimeUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 结算总表 前端控制器
 * </p>
 *
 * @author shenyuqing
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/totalSettlement")
public class TotalSettlementController {
    @Resource
    TotalSettlementService totalSettlementService;
    @Resource
    OrganizationalStructureService organizationalStructureService;
    @Resource
    EquipmentManagementService equipmentManagementService;
    /**
     * 结算管理单价设置
     * @param totalSettlement
     * @return
     */
    @PostMapping("adds")
    public ApiResult add(@RequestBody TotalSettlement totalSettlement){
        totalSettlementService.add(totalSettlement);
        return ApiResult.success();
    }

    /**
     * 单价设置的一条数据
     * @param totalSettlement
     * @return
     */
    @PostMapping("one")
    public ApiResult one(@RequestBody TotalSettlement totalSettlement){
        List<TotalSettlement> list = totalSettlementService.list(new QueryWrapper<TotalSettlement>()
                .eq("year", totalSettlement.getYear())
                .eq("month", totalSettlement.getMonth())
                .eq("site_id", totalSettlement.getSiteId()));
        if (list.isEmpty()){
            TotalSettlement totalSettlement1 = new TotalSettlement();
            OrganizationalStructure byId = organizationalStructureService.getById(totalSettlement.getSiteId());
            OrganizationalStructure qu = organizationalStructureService.getById(byId.getQuId());
            OrganizationalStructure shi = organizationalStructureService.getById(byId.getShiId());
            OrganizationalStructure sheng = organizationalStructureService.getById(byId.getShengId());
            OrganizationalStructure daqu = organizationalStructureService.getById(byId.getRegionId());
            OrganizationalStructure qudao = organizationalStructureService.getById(byId.getChannelId());

            totalSettlement1.setRegionName(daqu.getName());
            totalSettlement1.setRegionId(byId.getRegionId());
            totalSettlement1.setChannelMerchantsId(byId.getChannelId());
            totalSettlement1.setChannelMerchantsName(qudao.getName());
            totalSettlement1.setAreaName(sheng.getName()+shi.getName()+qu.getName());
            totalSettlement1.setCustomName(byId.getCustomerName());
            totalSettlement1.setSiteName(byId.getName());
            totalSettlement1.setYear(totalSettlement.getYear());
            totalSettlement1.setMonth(totalSettlement.getMonth());
            totalSettlement1.setAccountNumber(byId.getCustomerAccountNumber());
            totalSettlement1.setPowerGenerationUnit(byId.getPowerGenerationUnit());
            totalSettlement1.setSiteId(totalSettlement.getSiteId());
            List<EquipmentManagement> list1 = equipmentManagementService.list(new QueryWrapper<EquipmentManagement>()
                    .eq("site_id", totalSettlement.getSiteId())
                            .eq("examine",1)
                            .eq("isjf",1)
                            .isNull("delete_examine")
                    .in("equipment_type",6,7));
            List<BillingInformationSettings> bill = new ArrayList<>();
            if (!list1.isEmpty()&&list1.size()==1){
                for (EquipmentManagement equipmentManagement : list1) {
                    BillingInformationSettings settings = new BillingInformationSettings();
                    settings.setJfjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setPdjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setGfjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setDgjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setZjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setDbm(equipmentManagement.getName());
                    if (equipmentManagement.getEquipmentType()==6)
                        settings.setSworfd(0);
                    if (equipmentManagement.getEquipmentType()==7)
                        settings.setSworfd(1);
                    bill.add(settings);
                }
                if (list1.get(0).getEquipmentType()==6){
                    BillingInformationSettings settings = new BillingInformationSettings();
                    settings.setJfjld("/");
                    settings.setPdjld("/");
                    settings.setGfjld("/");
                    settings.setDgjld("/");
                    settings.setZjld("/");
                    settings.setDbm("发电电表");
                    settings.setSworfd(1);
                    bill.add(settings);
                }else {
                    BillingInformationSettings settings = new BillingInformationSettings();
                    settings.setJfjld("/");
                    settings.setPdjld("/");
                    settings.setGfjld("/");
                    settings.setDgjld("/");
                    settings.setZjld("/");
                    settings.setDbm("上网电表");
                    settings.setSworfd(0);
                    bill.add(settings);
                }
            }else if (list1.size()>1){
                for (EquipmentManagement equipmentManagement : list1) {
                    BillingInformationSettings settings = new BillingInformationSettings();
                    settings.setJfjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setPdjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setGfjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setDgjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setZjld(equipmentManagement.getMeasurementPointLocation());
                    settings.setDbm(equipmentManagement.getName());
                    if (equipmentManagement.getEquipmentType()==6)
                        settings.setSworfd(0);
                    if (equipmentManagement.getEquipmentType()==7)
                        settings.setSworfd(1);
                    bill.add(settings);
                }
            }else if (list1.isEmpty()){
                BillingInformationSettings settings = new BillingInformationSettings();
                settings.setJfjld("/");
                settings.setPdjld("/");
                settings.setGfjld("/");
                settings.setDgjld("/");
                settings.setZjld("/");
                settings.setDbm("上网电表");
                settings.setSworfd(0);
                bill.add(settings);
                BillingInformationSettings settings1 = new BillingInformationSettings();
                settings1.setJfjld("/");
                settings1.setPdjld("/");
                settings1.setGfjld("/");
                settings1.setDgjld("/");
                settings.setZjld("/");
                settings1.setDbm("发电电表");
                settings1.setSworfd(1);
                bill.add(settings1);
            }



            totalSettlement1.setBillingInformationSettings(bill);
//            int year = 2022;
//            int month = 5;
            Calendar cal = Calendar.getInstance();
            cal.set(totalSettlement.getYear(), totalSettlement.getMonth() - 1, 1);
            int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, firstDay);

            Calendar cal1 = Calendar.getInstance();
            cal1.set(totalSettlement.getYear(), totalSettlement.getMonth() - 1, 1);
            int lastDay = cal1.getActualMaximum(Calendar.DAY_OF_MONTH);
            cal1.set(Calendar.DAY_OF_MONTH, lastDay);

            totalSettlement1.setSettlementCycleBegin(cal.getTime());
            totalSettlement1.setSettlementCycleOver(cal1.getTime());
            return ApiResult.success(totalSettlement1);
        }
        TotalSettlement one =  totalSettlementService.one(totalSettlement);
        return ApiResult.success(one);
    }

    /**
     * 结算列表
     * @param pageVo
     * @return
     */
    @PostMapping("list")
    public ApiResult list(@RequestBody PageVo pageVo){
        IPage<TotalSettlement> page = totalSettlementService.selList(pageVo);
        return ApiResult.success(page);
    }

    /**
     * 历史记录
     * @param pageVo
     * @return
     */
    @PostMapping("listHistory")
    public ApiResult listHistory(@RequestBody PageVo pageVo){
        IPage<TotalSettlement> page = new Page<>(pageVo.getPage(),pageVo.getSize());
        QueryWrapper<TotalSettlement> wrapper = new QueryWrapper<>();
        wrapper.eq("year",pageVo.getYear());
        wrapper.eq("month",pageVo.getMonth());
        wrapper.eq("site_id",pageVo.getSiteId());
        wrapper.eq("save_or_execution",1);
        wrapper.orderByDesc("create_time");
        page =  totalSettlementService.page(page,wrapper);
        return ApiResult.success(page);
    }

    /**
     * 详情
     * @param totalSettlement
     * @return
     */
    @PostMapping("details")
    public ApiResult detail(@RequestBody TotalSettlement totalSettlement){
        TotalSettlement one =  totalSettlementService.detail(totalSettlement);
        return ApiResult.success(one);
    }


    @PostMapping("/downloads")
    public void download(@RequestBody @Valid TotalSettlement totalSettlement, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        TotalSettlement byId = totalSettlementService.getById(totalSettlement.getId());
        // 防止日志记录获取session异常
        request.getSession();
        // 设置编码格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(byId.getYear()+"年"+byId.getMonth()+"月"+byId.getSiteName()+"结算清单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        totalSettlementService.download(totalSettlement, response);
    }

    /**
     * 线下缴费
     * @param totalSettlement
     * @return
     */
    @PostMapping("fee")
    public ApiResult fee(@RequestBody TotalSettlement totalSettlement){
        User user = UserThreadLocal.get();
        totalSettlement.setUserId(user.getId());
        totalSettlement.setAccount(user.getUsername());
        totalSettlement.setUsername(user.getNickname());
        totalSettlement.setPhone(user.getPhone());
        totalSettlement.setFeeDate(DateTimeUtil.dqsj());
        totalSettlement.setFeeType(1);
        totalSettlement.setFeeState(1);
        totalSettlementService.updateById(totalSettlement);
        return ApiResult.success();
    }

    /**
     * 缴费记录
     * @param pageVo
     * @return
     */
    @PostMapping("record")
    public ApiResult record(@RequestBody PageVo pageVo){
        Page<TotalSettlement> page =  totalSettlementService.record(pageVo);
        return ApiResult.success(page);
    }

    /**
     * 导出
     * @param pageVo
     * @return
     */
    @PostMapping("excel")
    public ApiResult excel(@RequestBody PageVo pageVo){
        totalSettlementService.excel(pageVo);
        return ApiResult.success();
    }

    /**
     * 结算管理单价设置改
     * @param totalSettlement
     * @return
     */
    @PostMapping("add")
    public ApiResult addgai(@RequestBody TotalSettlement totalSettlement){
        totalSettlementService.addgai(totalSettlement);
        return ApiResult.success();
    }

    /**
     * 详情
     * @param totalSettlement
     * @return
     */
    @PostMapping("detail")
    public ApiResult details(@RequestBody TotalSettlement totalSettlement){
        TotalSettlement one =  totalSettlementService.details(totalSettlement);
        return ApiResult.success(one);
    }

    @PostMapping("/download")
    public void downloads(@RequestBody @Valid TotalSettlement totalSettlement, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        TotalSettlement byId = totalSettlementService.getById(totalSettlement.getId());
        // 防止日志记录获取session异常
        request.getSession();
        // 设置编码格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(byId.getYear()+"年"+byId.getMonth()+"月"+byId.getSiteName()+"结算清单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        totalSettlementService.downloads(totalSettlement, response);
    }
}

